﻿using System;
using Domain.Core;
using Domain.MainModule.Entities;
using Domain.MainModule.Cities;

namespace Application.MainModule.CitiesManagement
{
    public class CityManagementService : ICityManagementService, IDisposable
    {
        #region private properties

        private ICityRepository CityRepository
        {
            get;
            set;
        }

        #endregion

        #region constructor

        /// <summary>
        /// Default constructor for CityService.
        /// </summary>
        /// <param name="employeeRepository">CityRepository dependency. Usually this is resolved by IoC</param>
        public CityManagementService(ICityRepository cityRepository)
        {
            if (cityRepository == (ICityRepository)null)
            {
                throw new ArgumentNullException(Resources.Messages.exception_DependenciesAreNotInitialized);
            }

            this.CityRepository = cityRepository;
        }

        #endregion

        #region ICountryService implementations

        public void AddCity(City city)
        {
            IUnitOfWork unitOfWork = this.CityRepository.UnitOfWork as IUnitOfWork;
            this.CityRepository.Add(city);
            unitOfWork.Commit();
        }

        public void ChangeCity(City city)
        {
            IUnitOfWork unitOfWork = this.CityRepository.UnitOfWork as IUnitOfWork;
            this.CityRepository.Modify(city);
            unitOfWork.CommitAndRefreshChanges();
        }

        public City FindCityByName(string cityName)
        {
            CityNameSpecification cityNameSpecification = new CityNameSpecification(cityName);
            return this.CityRepository.FindCity(cityNameSpecification);
        }

        #endregion

        #region IDisposable implementations

        /// <summary>
        /// Dispose associated context with this domain service.
        /// </summary>
        public void Dispose()
        {
            if (this.CityRepository != null && this.CityRepository.UnitOfWork != null)
            {
                this.CityRepository.UnitOfWork.Dispose();
            }
        }

        #endregion
    }
}
